package com.example.lets;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ResideMenu.ResideMenu;
import com.ResideMenu.ResideMenuItem;
import com.gc.materialdesign.views.ButtonFloat;
import com.github.ksoichiro.android.observablescrollview.ObservableListView;
import com.github.ksoichiro.android.observablescrollview.ObservableScrollView;
import com.github.ksoichiro.android.observablescrollview.ObservableScrollViewCallbacks;
import com.github.ksoichiro.android.observablescrollview.ScrollState;
import com.github.ksoichiro.android.observablescrollview.ScrollUtils;
import com.nineoldandroids.view.ViewHelper;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobDate;
import cn.bmob.v3.listener.FindListener;

public class HomeActivity extends BaseActivity implements ObservableScrollViewCallbacks {

	private View mFlexibleSpaceView;
	private Toolbar mToolbarView;
	public static ObservableListView homeList;
	private LinearLayout mSearchView;
	private int mFlexibleSpaceHeight;
	private boolean hasQuery = false;
	private ResideMenu resideMenu;
	private RefreshableView header;
	private ArrayList<HashMap<String, Object>> listItem;
	private MyAdapter adapter;


	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		return resideMenu.dispatchTouchEvent(ev);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_home);

		resideMenu = new ResideMenu(this);
		resideMenu.setBackground(R.drawable.bg_material);
		resideMenu.attachToActivity(this);
		resideMenu.setSwipeDirectionDisable(ResideMenu.DIRECTION_RIGHT);

		// create menu items;
		String titles[] = {"个人中心", "参与的活动", "发起的活动", "退出登录"};
		int icon[] = {R.drawable.icon_home, R.drawable.icon_profile, R.drawable.icon_calendar, R.drawable.icon_settings};

		for (int i = 0; i < titles.length; i++) {
			ResideMenuItem item = new ResideMenuItem(this, icon[i], titles[i]);

            if(i == 0) {//????????
                item.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent();
                        intent.setClass(HomeActivity.this, MeActivity.class);
                        startActivity(intent);
						HomeActivity.this.finish();
                    }
                });
            }

            else if (i == 1){//???????
                item.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        BmobUser currentUser = BmobUser.getCurrentUser(HomeActivity.this);
                        final String id = currentUser.getObjectId();
                        Intent intent = new Intent(HomeActivity.this, SearchResult.class);
                        intent.putExtra("mode", "joined");
                        intent.putExtra("input", id);
                        startActivity(intent);
                    }
                });
            }
            else if (i == 2){//??????
                 item.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        BmobUser currentUser = BmobUser.getCurrentUser(HomeActivity.this);
                        final String id = currentUser.getObjectId();
                        Intent intent = new Intent(HomeActivity.this, SearchResult.class);
                        intent.putExtra("mode", "sponsored");
                        intent.putExtra("input", id);
                        startActivity(intent);
                    }
                });
            }
            else if (i == 3){//??????
                item.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        BmobUser.logOut(HomeActivity.this);
                        Intent intent = new Intent();
                        intent.setClass(HomeActivity.this, LoginActivity.class);
                        startActivity(intent);
						HomeActivity.this.finish();
                    }
                });
            }
			resideMenu.addMenuItem(item,  ResideMenu.DIRECTION_LEFT); // or  ResideMenu.DIRECTION_RIGHT

		}

		setSupportActionBar((Toolbar) findViewById(R.id.home_toolbar));
		ActionBar ab = getSupportActionBar();

		if (ab != null) {
			getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		}

		mFlexibleSpaceView = findViewById(R.id.flexible_space);
		mSearchView = (LinearLayout) findViewById(R.id.search_box);
		mSearchView.setTranslationY(getActionBarSize());

		setTitle(null);
		mToolbarView = (Toolbar) findViewById(R.id.home_toolbar);

		((TextView) findViewById(R.id.home_title)).
				setText(BmobUser.getCurrentUser(this, User.class).getNickname());
		mToolbarView.setNavigationIcon(R.drawable.list_icon_white);
		mToolbarView.setNavigationOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				resideMenu.openMenu(ResideMenu.DIRECTION_LEFT);
			}
		});

		homeList = (ObservableListView) findViewById(R.id.home_list);
		homeList.setScrollViewCallbacks(this);

		mFlexibleSpaceView.setClickable(false);
		mFlexibleSpaceHeight = getResources().getDimensionPixelSize(R.dimen.flexible_space_height);
		int flexibleSpaceAndToolbarHeight = mFlexibleSpaceHeight + getActionBarSize();
		RefreshableView.hideHeaderHeight = flexibleSpaceAndToolbarHeight;

		ScrollUtils.addOnGlobalLayoutListener(mSearchView, new Runnable() {
			@Override
			public void run() {
				updateFlexibleSpaceText(homeList.getCurrentScrollY());
			}
		});

		LayoutInflater inflater = LayoutInflater.from(HomeActivity.this);
		View tableButtons = inflater.inflate(R.layout.types_group_table_layout, null);
		header = new RefreshableView(this, null);
		//ViewGroup.MarginLayoutParams headerLayoutParams = (ViewGroup.MarginLayoutParams) header.getLayoutParams();
		//headerLayoutParams.topMargin = RefreshableView.hideHeaderHeight;
		//header.setLayoutParams(headerLayoutParams);
		//header.getLayoutParams().height = flexibleSpaceAndToolbarHeight;
		//header.setPadding(0, flexibleSpaceAndToolbarHeight, 0, 0);
		header.setClickable(false);
		header.setOnRefreshListener(new RefreshableView.PullToRefreshListener() {
			@Override
			public void onRefresh() {

				BmobQuery<UserActivity> query = new BmobQuery<UserActivity>();
				query.addWhereNotEqualTo("name", "");
				query.setLimit(100);
				query.findObjects(HomeActivity.this, new FindListener<UserActivity>() {

					@Override
					public void onSuccess(List<UserActivity> object) {
						listItem.clear();
						for (UserActivity activity : object) {
							HashMap<String, Object> map = new HashMap<String, Object>();

							map.put("ItemSponsor", activity.getSponsorName());
							map.put("ItemPicFileName", activity.getPicFilename());
							map.put("ItemTitle", activity.getName());
							map.put("ItemText", activity.getDescription());
							map.put("number", activity.getPeopleNumber());
							map.put("sponsorId", activity.getSponsorId());
							map.put("place", activity.getPlace());
							map.put("time", activity.getStartTime().getDate());
							map.put("type", activity.getType());
							map.put("id", activity.getObjectId());
							listItem.add(map);
						}

						adapter.notifyDataSetChanged();
						header.finishRefreshing();
					}

					@Override
					public void onError(int code, String msg) {
						Toast.makeText(HomeActivity.this, "下载失败，网络异常！", Toast.LENGTH_SHORT).show();
						header.finishRefreshing();
					}
				});
			}
		}, 0);
		View paddingView = inflater.inflate(R.layout.homelist_padding, null);
		paddingView.setPadding(0, flexibleSpaceAndToolbarHeight, 0, 0);
		paddingView.setClickable(false);

		homeList.addHeaderView(paddingView, null, false);
		homeList.addHeaderView(header, null, false);
		homeList.addHeaderView(tableButtons, null, false);

		mFlexibleSpaceView.getLayoutParams().height = flexibleSpaceAndToolbarHeight;

		// Float button
		ButtonFloat initiateButton = (ButtonFloat) HomeActivity.this.findViewById(R.id.home_initiate_event_button);
		initiateButton.setRippleSpeed(10.0f);
		// set icon
		ImageView imageView = new ImageView(HomeActivity.this);
		Drawable drawable = getResources().getDrawable(R.drawable.initiate_event_button);
		imageView.setImageDrawable(drawable);
		RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
				RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
		params.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
		imageView.setLayoutParams(params);
		initiateButton.addView(imageView);
		initiateButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(HomeActivity.this, InitiateEventActivity.class);
				startActivity(intent);
				HomeActivity.this.finish();
			}
		});

        TextView search = (TextView) this.findViewById(R.id.search_content);
        search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(HomeActivity.this, SearchActivity.class);
                startActivity(intent);
            }
        });

        mToolbarView.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
			@Override
			public boolean onMenuItemClick(MenuItem menuItem) {
				Intent intent = new Intent(HomeActivity.this, SearchActivity.class);
				startActivity(intent);
				return false;
			}
		});


		ImageButton sportButton = (ImageButton) HomeActivity.this.findViewById(R.id.SportButton);
		sportButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				String type = "sport";
				Intent intent = new Intent(HomeActivity.this, SearchResult.class);
				intent.putExtra("mode", "type");
				intent.putExtra("input", type);
				startActivity(intent);
			}
		});

		ImageButton foodButton = (ImageButton) HomeActivity.this.findViewById(R.id.FoodButton);
		foodButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				String type = "food";
				Intent intent = new Intent();
				intent.setClass(HomeActivity.this, SearchResult.class);
				intent.putExtra("mode", "type");
				intent.putExtra("input", type);
				startActivity(intent);
			}
		});

		ImageButton tourButton = (ImageButton) HomeActivity.this.findViewById(R.id.TravelButton);
		tourButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				String type = "tour";
				Intent intent = new Intent();
				intent.setClass(HomeActivity.this, SearchResult.class);
				intent.putExtra("mode", "type");
				intent.putExtra("input", type);
				startActivity(intent);
			}
		});

		ImageButton studyButton = (ImageButton) HomeActivity.this.findViewById(R.id.StudyButton);
		studyButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				String type = "study";
				Intent intent = new Intent();
				intent.setClass(HomeActivity.this, SearchResult.class);
				intent.putExtra("mode", "type");
				intent.putExtra("input", type);
				startActivity(intent);
			}
		});

		ImageButton gameButton = (ImageButton) HomeActivity.this.findViewById(R.id.GameButton);
		gameButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				String type = "game";
				Intent intent = new Intent();
				intent.setClass(HomeActivity.this, SearchResult.class);
				intent.putExtra("mode", "type");
				intent.putExtra("input", type);
				startActivity(intent);
			}
		});

		ImageButton movieButton = (ImageButton) HomeActivity.this.findViewById(R.id.MovieButton);
		movieButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				String type = "movie";
				Intent intent = new Intent();
				intent.setClass(HomeActivity.this, SearchResult.class);
				intent.putExtra("mode", "type");
				intent.putExtra("input", type);
				startActivity(intent);
			}
		});

		if (!hasQuery) {
			loadActivities();
			hasQuery = true;
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.home, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public void onScrollChanged(int scrollY, boolean firstScroll, boolean dragging) {
		/*if (scrollY >= 0 && dragging) {
			AbsListView.LayoutParams linearParams =(AbsListView.LayoutParams) pullHeader.getLayoutParams();
			linearParams.height = scrollY;
			pullHeader.setLayoutParams(linearParams);
		}*/
		updateFlexibleSpaceText(scrollY);
	}

	@Override
	public void onDownMotionEvent() {
	}

	@Override
	public void onUpOrCancelMotionEvent(ScrollState scrollState) {
	}

	private void updateFlexibleSpaceText(final int scrollY) {

		ViewHelper.setTranslationY(mFlexibleSpaceView, -scrollY);
		int adjustedScrollY = (int) ScrollUtils.getFloat(scrollY, 0, mFlexibleSpaceHeight);
		float scale = /*maxScale **/ ((float) mFlexibleSpaceHeight - adjustedScrollY) / mFlexibleSpaceHeight;

		ViewHelper.setPivotY(mSearchView, 0);
		ViewHelper.setScaleX(mSearchView, scale);
		ViewHelper.setScaleY(mSearchView, scale);
	}

	private void loadActivities() {

		BmobQuery<UserActivity> query = new BmobQuery<UserActivity>();
		// ??????��?
		//query.addWhereNotEqualTo("name", "");
		Date currentTime = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String dateString = sdf.format(currentTime);
		Date date  = null;
		try {
			date = sdf.parse(dateString);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		query.addWhereGreaterThanOrEqualTo("startTime", new BmobDate(date));
		// ????50?????????????????????????????10??????
		query.setLimit(100);
		// ??��??????
		query.findObjects(this, new FindListener<UserActivity>() {

			@Override
			public void onSuccess(List<UserActivity> object) {
				listItem = new ArrayList<HashMap<String, Object>>();

				for (UserActivity activity : object) {
					HashMap<String, Object> map = new HashMap<String, Object>();

					int dateLength = activity.getStartTime().getDate().length();
					map.put("ItemSponsor", activity.getSponsorName());
					map.put("ItemPicFileName", activity.getPicFilename());
					map.put("ItemTitle", activity.getName());
					map.put("ItemText", activity.getDescription());
					map.put("number", activity.getPeopleNumber());
					map.put("sponsorId", activity.getSponsorId());
					map.put("place", activity.getPlace());
					map.put("time", activity.getStartTime().getDate().substring(0, dateLength-3));
					map.put("type", activity.getType());
					map.put("id", activity.getObjectId());
					listItem.add(map);
				}

				adapter = new MyAdapter(HomeActivity.this, listItem);
				homeList.setAdapter(adapter);
				homeList.setOnItemClickListener(new AdapterView.OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> parent, View view,
											int position, long id) {

						if (position < 3) return;
						position -= 3;

						String title = (String) listItem.get(position).get("ItemTitle");
						String description = (String) listItem.get(position).get("ItemText");
						String picFileName = (String) listItem.get(position).get("ItemPicFileName");
						String sponsorId = (String) listItem.get(position).get("sponsorId");
						String type = (String) listItem.get(position).get("type");
						String place = (String) listItem.get(position).get("place");
						String time = (String) listItem.get(position).get("time");
						String actiId = (String) listItem.get(position).get("id");

						Intent intent = new Intent(HomeActivity.this, EventActivity.class);
						intent.putExtra("title", title);
						intent.putExtra("description", description);
						intent.putExtra("picFileName", picFileName);
						intent.putExtra("sponsorId", sponsorId);
						intent.putExtra("place", place);
						intent.putExtra("time", time);
						intent.putExtra("type", type);
						intent.putExtra("id", actiId);

						startActivity(intent);
					}

				});
			}

			@Override
			public void onError(int code, String msg) {
				Toast.makeText(HomeActivity.this, "下载失败，网络异常！", Toast.LENGTH_SHORT).show();
			}
		});
	}

	public void onBackPressed() {
		Intent intent= new Intent(Intent.ACTION_MAIN);
		intent.addCategory(Intent.CATEGORY_HOME);
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
		startActivity(intent);
		return;
	}
}
